package com.eva.androidlibrary.image;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.ExifInterface;

import com.eva.androidlibrary.utils.FileUtil;
import com.eva.androidlibrary.utils.UIUtil;

import java.io.File;
import java.io.IOException;

/**
 * 图片处理器，旋转、剪裁等
 *
 * @author GUXIA318
 * @date 2015-10-09 20:16
 */
public class ImageProcesser {

    /**
     * 获取图片的旋转角度
     *
     * @param path 图片的绝对路径
     * @return 图片的旋转角度
     */
    public static int getBitmapDegree(String path) {
        int degree = 0;
        try {
            // 从指定路径下读取图片，并获取其EXIF信息
            ExifInterface exifInterface = new ExifInterface(path);
            // 获取图片的旋转信息
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                    ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }

    public static void rotateBitmap(File sourceFile, Activity context) {
        String filePath = sourceFile.getPath();
        File file = sourceFile;
        Bitmap result = null;
        Bitmap source = null;
        int degree = getBitmapDegree(filePath);
        if (degree != 0) {
            ImageHelper imageHelper = ImageHelper.getInstance(context);
            try {
                int size = UIUtil.getWindowWidth(context);
                source = imageHelper.getImage(filePath, size, size);
                // 根据旋转角度，生成旋转矩阵
                Matrix matrix = new Matrix();
                matrix.postRotate(degree);
                result = Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
//                file = FileUtil.saveBitmap(context, result, null, filePath, Bitmap.CompressFormat.JPEG);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (source != null) {
                    source.recycle();
                }

                if (result != null) {
                    result.recycle();
                }
            }
        }
    }
}
